package cz.muni.fi.pa165.sme.web.panels.user;

import cz.muni.fi.pa165.sme.api.UserService;
import cz.muni.fi.pa165.sme.api.to.UserTO;
import cz.muni.fi.pa165.sme.web.common.ErrorBehavior;
import cz.muni.fi.pa165.sme.web.fo.UserFO;
import cz.muni.fi.pa165.sme.web.pages.TemplatePage;
import cz.muni.fi.pa165.sme.web.pages.sportActivityRecord.RecordListPage;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.springframework.core.convert.ConversionService;

/** @author jirankova */
public class LoginForm extends Panel {

	@SpringBean
	private UserService userService;

	@SpringBean(name = "conversionServiceFe")
	private ConversionService conversionService;

	public LoginForm(final String id, final IModel<UserFO> model) {
		super(id, model);

		//login field
		final FormComponent<String> login = new TextField<String>("login");
		login.setRequired(true);

		// password field
		final PasswordTextField password = new PasswordTextField("password");
		password.setRequired(false);

		//login form
		final Form<UserFO> form = new Form<UserFO>("loginForm", model) {
			@Override
			protected void onSubmit() {
				String password1 = model.getObject().getPassword();
				model.getObject().setPassword(org.apache.commons.codec.digest.DigestUtils.sha256Hex(password1));
				AuthenticatedWebSession session = AuthenticatedWebSession.get();
				if (session.signIn(getModelObject().getLogin(), getModelObject().getPassword())) {
					setDefaultResponsePageIfNecessary();
				} else {
					error(getString("login.failed.badcredentials"));
				}
			}
		};
		form.add(login);
		form.add(password);
		add(form);

		form.visitChildren(FormComponent.class, new IVisitor<FormComponent<?>, IVisit<Void>>() {
			@Override
			public void component(final FormComponent<?> object, final IVisit<IVisit<Void>> visit) {
				object.add(new ErrorBehavior());
				visit.dontGoDeeper();
			}
		});

		final FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");
		feedbackPanel.setOutputMarkupId(true);
		add(feedbackPanel);
	}

	private void setDefaultResponsePageIfNecessary() {
		if (!continueToOriginalDestination()) {
			setResponsePage(RecordListPage.class);
		}
	}
}
